<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item class="merge-item">
        <el-select v-model="conditionType" style="width: 170px; margin-right: 2px;">
          <el-option label="退瓶单号" value="backCode" />
          <el-option label="客户电话" value="contactPhone" />
          <el-option label="客户编号" value="csmCode" />
          <el-option label="客户名称" value="csmName" />
          <el-option label="客户地址" value="contactAddress" />
        </el-select>
        <el-input v-model.trim="csmText" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="责任机构:" prop="orgSNNo">
        <el-tree-select
          v-model="query.orgSNNo"
          :clearable="true"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <!-- <el-form-item label="处理人:" prop="userId">
        <el-select v-model="query.userId" :loading="$loadingPlugin.getOwnersList" style="width: 100%;" filterable placeholder="请选择" clearable>
          <el-option
            v-for="item in ownersList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="状态:" prop="rstatus">
        <el-select v-model="query.rstatus" filterable placeholder="请选择" clearable>
          <el-option
            v-for="item in rstatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :table-form-merge="2" label="登记时间:">
        <el-date-picker
          v-model="date"
          :clearable="false"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
        />
      </el-form-item>
      <el-form-item label="客户类型:" prop="csmType">
        <el-select v-model="query.csmType" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in csmTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button v-permission="1" type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button v-permission="2" type="primary" icon="el-icon-download" @click="exportFile">导出</el-button>
        <!-- <el-button v-permission="3" type="primary" @click="print">打印</el-button> -->
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <detail ref="detail" />
    <transfer-order ref="transferOrder" />
    <press-order ref="pressOrder" />
    <remark-order ref="remarkOrder" />
    <back-order ref="backOrder" />
    <cylinder-detail ref="cylinderDetail" />
    <popups
      ref="popups"
      :ent-type-list="entTypeList"
      :tree-data="treeData"
      :calc-type-list="calcTypeList"
      :payment-method-list="paymentMethodList"
      :pay-status-list="payStatusList"
      :paymen-fil-list="paymenFilList"
      :customer-type="customerType"
    />
    <csm-detail
      ref="csmDetail"
      :tree-data="treeData"
      :calc-type-list="calcTypeList"
      :paymen-fil-list="paymenFilList"
    />
  </div>
</template>

<script>
  import {
    queryMap,
    queryBackBottleTaskList,
    queryOwnersList,
    queryCsmTypeMap,
    queryBackBottleStatusMap,
    queryVisitStatusMap,
    queryCallCheckMap,
    queryReturnManageListExport,
    givebackBottleCheckOut,
    givebackQueryDepositResult,
    queryGivebackSound
  } from '@/api'
  import { formatColumnMap, parseTime } from '@/utils'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import moment from 'dayjs'
  import Detail from './components/Detail'
  import TransferOrder from './components/TransferOrder'
  import PressOrder from '../../components/PressOrderModal'
  import RemarkOrder from './components/RemarkOrder'
  import BackOrder from './components/BackOrder'
  import Popups from '../../customerCenter/depositManage/components/Popups'
  import CsmDetail from '@/views/components/CsmDetailModal/index'
  import CylinderDetail from '@/views/components/cylinderDetail/index'
  const colorObj = {
    1: 'color:#ff0000;',
    2: 'color:#cc33ff;',
    5: 'color:#389E0D;',
    7: 'color:#ff9933;',
    8: 'color:#ff0000;',
    10: 'color:#0066ff;'
  }

  export default {
    name: 'returnBottle',
    components: {
      Detail, TransferOrder, PressOrder, RemarkOrder, BackOrder, CylinderDetail, Popups, CsmDetail
    },
    data() {
      return {
        entTypeList: [], // 客户类型
        calcTypeList: [], // 收款方式
        paymentMethodList: [], // 支付方式
        paymenFilList: [], // 已过滤的支付方式
        payStatusList: [], // 支付状态
        customerType: [], //  客户类型
        actionColWidth: 80,
        treeData: [],
        csmTypeMap: [],
        rstatusMap: [],
        formPlatMap: [],
        visitStatusMap: [],
        callCheckMap: [],
        ownersList: [],
        conditionType: 'contactPhone',
        date: [moment().startOf('day'), moment().endOf('day')],
        csmText: '',
        query: {
          orgSNNo: '', // 所属机构orgSNNo
          userId: '',
          rstatus: ''
        },
        searchParams: {},
        roleTypeList: [],
        tableData: {
          total: 0,
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'exportDomain'
      ]),
      column: function() {
        return [
          {
            type: 'index',
            align: 'center'
          },
          {
            prop: 'backCode',
            label: '退瓶单号',
            width: 150,
            render: (h, { row }) => <el-link underline={false} onClick={() => this.openDetail(row)}>{row.backCode}</el-link>
          },
          {
            prop: 'formPlat',
            label: '来源',
            width: 90,
            render: (h, { row }) => <span>{ row.formPlat && formatColumnMap(this.formPlatMap, 'value', row.formPlat, 'desc') }</span>
          },
          {
            prop: 'recChipIDS',
            label: '气瓶编码',
            width: 120,
            render: (h, { row }) => {
              if (!row.recChipIDS) {
                return
              }
              if (row.recChipIDS.indexOf(',') === -1) {
                return (<el-link underline={false} onClick={() => this.openCylinderDetail(row.recChipIDS)}>{row.recChipIDS}</el-link>)
              }
              const list = row.recChipIDS.split(',')
              return h(
                'span', {},
                list.map((item, index) => {
                  return (<el-link underline={false} onClick={() => this.openCylinderDetail(item)}>{item}</el-link>)
                })
              )
            }
          },
          // {
          //   prop: 'recCodeIDS',
          //   label: '气瓶编码',
          //   width: 120,
          //   render: (h, { row }) => <span underline={false}>{row.recCodeIDS}</span>
          // },
          {
            prop: 'csmCode',
            label: '客户编号',
            width: 110,
            render: (h, { row }) => <el-link underline={false} onClick={() => this.openCsmDetail(row)}>{row.csmCode}</el-link>
          },
          {
            prop: 'csmName',
            width: 120,
            label: '客户名称'
          },
          {
            prop: 'csmType',
            label: '客户类型',
            render: (h, { row }) => <span>{ row.csmType && formatColumnMap(this.csmTypeMap, 'value', row.csmType, 'desc') }</span>
          },
          {
            prop: 'contact',
            label: '联系人'
          },
          {
            prop: 'contactAddress',
            label: '联系地址',
            width: 110,
            showOverflowTooltip: true
          },
          {
            prop: 'contactPhone',
            label: '联系电话',
            width: 110
          },
          {
            prop: 'orgName',
            width: 160,
            label: '责任机构',
            showOverflowTooltip: true
          },
          {
            prop: 'depositCodes',
            label: '关联押金单',
            width: 200,
            render: (h, { row }) => {
              if (!row.depositCodes) {
                return
              }
              if (row.depositCodes.indexOf(',') === -1) {
                return (<el-link underline={false} onClick={() => this.showDeposit(row.depositCodes)}>{row.depositCodes}</el-link>)
              }
              const list = row.depositCodes.split(',')
              return h(
                'span', {},
                list.map((item, index) => {
                  return (<el-link underline={false} onClick={() => this.showDeposit(item)}>{item}</el-link>)
                })
              )
            }
          },
          {
            prop: 'bottleRefundFee',
            label: '取瓶费',
            render: (h, { row }) => (
            <span>{row.bottleRefundFee && row.bottleRefundFee.toFixed(2)}</span>
          )
          },
          {
            prop: 'userName',
            label: '处理人',
            showOverflowTooltip: true
          },
          {
            prop: 'answer',
            label: '登记人',
            showOverflowTooltip: true
          },
          {
            prop: 'createTime',
            label: '登记时间',
            width: 160,
            render: (h, { row }) => <span>{ row.createTime && parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}') }</span>
          },
          {
            prop: 'rstatus',
            label: '状态',
            width: 110,
            render: (h, { row }) => <span style={colorObj[row.rstatus]}>{ row.rstatus ? formatColumnMap(this.rstatusMap, 'value', row.rstatus, 'desc') : '未支付' }</span>
          },
          {
            prop: 'signDt',
            label: '完成时间',
            width: 160,
            render: (h, { row }) => <span>{ row.signDt && parseTime(row.signDt, '{y}-{m}-{d} {h}:{i}') }</span>
          },
          {
            prop: 'description',
            width: 160,
            label: '退瓶描述',
            showOverflowTooltip: true
          },
          {
            prop: 'remark',
            label: '备注',
            width: 110,
            showOverflowTooltip: true
          },
          // {
          //   prop: 'marker',
          //   label: '退单原因',
          //   width: 110,
          //   showOverflowTooltip: true
          // },
          {
            label: '操作',
            align: 'center',
            fixed: 'right',
            width: 80,
            render: (h, { row, $index }) => {
              return (
                <div>
                  <el-dropdown>
                    <span class='el-dropdown-link'>
                      更多<i class='el-icon-arrow-down el-icon--right'></i>
                    </span>
                    <el-dropdown-menu slot='dropdown'>
                      {(row.rstatus === 2 || row.rstatus === 6) && (
                        <el-dropdown-item>
                          <el-link v-permission='4' underline={false} size='mini' type='danger' onClick={() => this.openBackOrder(row, $index)}>
                            退单
                          </el-link>
                        </el-dropdown-item>)}
                      {(row.rstatus === 8) && (
                        <el-dropdown-item>
                          <el-link v-permission='8' underline={false} size='mini' onClick={() => this.confirm(row, $index)}>
                            确认
                          </el-link>
                        </el-dropdown-item>)}
                      {(row.rstatus === 2 || row.rstatus === 6) && (
                        <el-dropdown-item>
                          <el-link v-permission='5' underline={false} size='mini' onClick={() => this.openTransferOrder(row, $index)}>
                            转派
                          </el-link>
                        </el-dropdown-item>)}
                      {(row.rstatus !== -1 && row.rstatus !== 6 && row.rstatus !== 7 && row.rstatus !== 8 && row.rstatus !== 10) && (
                        <el-dropdown-item>
                          <el-link v-permission='6' underline={false} size='mini' onClick={() => this.openPressOrder(row, $index)}>
                            催单
                          </el-link>
                        </el-dropdown-item>)}
                      {(
                        <el-dropdown-item>
                          <el-link v-permission='7' underline={false} size='mini' onClick={() => this.openRemark(row, $index)}>
                            备注
                          </el-link>
                        </el-dropdown-item>)}
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>
              )
            }
          }
        ]
      }
    },

    watch: {
      $route: {
        handler: function(val, oldVal) {
          this.checkStatusByHash()
        },
        // 深度观察监听
        deep: true
      }
    },
    async created() {
      await Promise.all([this.getTreeData(), this.getOwnersList(), this.getBackBottleStatusMap(), this.getCsmTypeMap(), this.queryOptionsMap()])
      this.checkStatusByHash()
    },
    activated() {
      this.querySound()
      this.interval = setInterval(() => {
        this.querySound()
      }, 60000)
    },
    deactivated() {
      clearInterval(this.interval)
    },
    methods: {
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.getOwnersList(value)
      },
      // 根据路由参数设置状态
      checkStatusByHash() {
        const params = this.$route.query
        if (params) {
          if (params.type === '1') {
            this.query.rstatus = 6
          }
          if (params.type === '2') {
            this.query.rstatus = 2
          }
        }
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (this.date && this.date.length > 0) {
          query.createTime = this.date[0]
          query.createTimeEnd = this.date[1]
        }
        query[this.conditionType] = this.csmText
        const res = await queryBackBottleTaskList(query)
        this.searchParams = query
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      // 查询处理人列表
      async getOwnersList(org) {
        // const b = corpsetting.sp1 >> 2 & 0x01
        const res = await queryOwnersList({
          orgId: org ? org.orgId : -1
          // corpparm1: b
        })
        this.ownersList = res.data
      },
      // 查询客户类型枚举
      async getCsmTypeMap() {
        const res = await queryCsmTypeMap({})
        this.csmTypeMap = res.data
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res1, res2, res3, res4, res5] = await Promise.all([queryCsmTypeMap(), mergeAsyncFunc(queryMap, { enumName: 'CalcType' }), mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' }), mergeAsyncFunc(queryMap, { enumName: 'PayStatus' }), mergeAsyncFunc(queryMap, { enumName: 'CustomerType' })])
        this.entTypeList = res1.data // 客户类型
        this.calcTypeList = res2.data // 收款方式
        this.paymentMethodList = res3.data // 支付方式
        this.payStatusList = res4.data // 支付状态
        this.customerType = res5.data // 客户类型
        // 过滤支付方式
        const arr = ['现金', '微信支付', '支付宝', '银行支付']
        this.paymentMethodList.filter(item => {
          if (arr.includes(item.desc)) {
            this.paymenFilList.push(item)
          }
        })
      },
      // 查询状态枚举
      async getBackBottleStatusMap() {
        const res = await queryBackBottleStatusMap({})
        this.rstatusMap = JSON.parse(res.data.gBackStatus)
        this.formPlatMap = JSON.parse(res.data.formPlat)
      },
      // 查询回访结果枚举
      async getVisitStatusMap() {
        const res = await queryVisitStatusMap({})
        this.visitStatusMap = res.data
      },
      // 查询回访调查枚举
      async getCallCheckMap() {
        const res = await queryCallCheckMap({})
        this.callCheckMap = res.data
      },
      // 退单详情
      async openDetail(row) {
        await this.$refs.detail.open({ ...row, billCode: row.backCode, billType: 3 })
      },
      // 点击芯片编码/气瓶编码
      async openCylinderDetail(row) {
        await this.$refs.cylinderDetail.open(row)
        // await this.$refs.bottleDetail.open({
        //   ...row,
        //   chipCode: row[name]
        // }, null, 'returnManage')
      },
      // 客户详情
      async openCsmDetail(row) {
        await this.$refs.csmDetail.open(row, true)
      },
      // 押金详情
      async showDeposit(depositCode) {
        console.log('押金单号', depositCode)
        const res = await givebackQueryDepositResult({ depositCode })
        console.log('押金明细', res.data)
        this.$refs.popups.open(res.data, 'info')
      },
      // 点击催单
      async openPressOrder(row) {
        await this.$refs.pressOrder.open({ ...row, billCode: row.backCode, billType: 2, text: '处理' })
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 点击退单
      async openBackOrder(row) {
        await this.$refs.backOrder.open({ ...row })
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 点击确认
      async confirm(row) {
        this.$confirm('确认该气瓶是否已回到场站？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          const params = {
            backCode: row.backCode
          }
          const res = await givebackBottleCheckOut(params)
          if (res.status === 200) {
            this.$notify({
              title: '提示',
              message: '确认成功',
              type: 'success',
              duration: 2000
            })
            this.$refs.lbTable.fetch({ currentPage: 1 })
          }
        })
      },
      // 点击转派
      async openTransferOrder(row) {
        await this.$refs.transferOrder.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 点击备注
      async openRemark(row) {
        await this.$refs.remarkOrder.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 导出
      async exportFile() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.column))
          copyColumn.pop()
          const str = {}
          copyColumn.forEach((item) => {
            str[item.prop] = item.label
          })
          queryReturnManageListExport({
            paramInfo: _this._getQuery(_this.searchParams),
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      // 打印
      print() {

      },
      // 查询是否需要播放语音
      async querySound() {
        const query = {
          rstatus: 1
        }
        const params = {
          rstatus: 8
        }
        const [res1, res2] = await Promise.all([queryGivebackSound(query), queryGivebackSound(params)])
        if (res1.data && JSON.stringify(res1.data) !== '{}') {
          const dom = document.getElementById('newReturnBottle')
          dom.play()
        }
        setTimeout(() => {
          if (res2.data && JSON.stringify(res2.data) !== '{}') {
            const dom = document.getElementById('newReturnBottleFinish')
            dom.play()
          }
        }, 5000)
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach((it) => {
                width += it.offsetWidth + 10
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.el-form-item .el-form-item {
  margin-bottom: 0;
}
.merge-item {
  /deep/ .el-form-item__content {
    display: flex;
  }
}
.btn-group {
  display: flex;
  justify-content: space-between;
}
</style>
